Introduction to Python and Jupyter Notebook

Install

We will use Anaconda which contains Python, Jupyter Notebooks, and common libraries.

Download Anaconda from https://www.continuum.io/downloads. Choose Python 3.5 installer 64-bit (or 32-bit if you are unsure).

Hello World!

Lets make sure everything is working.


In [ ]:
print("Hello World!")

In [ ]:
# We can write comments like this.
print("Hello World!") # Or here. You can write anything you want.

# It's a good way of describing what your code does.

In [ ]:
# Note: we can't use upper case. We will get a "NameError".
PRINT("Hello World!")

Jupyter Notebooks

Some things are specific to Jupyter Notebooks, like these:

Keyboard Shortcuts

  • Ctrl+Enter = run cell
  • ESC = exit out of a cell
  • Tab = autocomplete
  • a = insert cell above
  • b = insert cell below
  • dd = delete cell

The Jupyter Notebook files are saved on your computer, in your home directory.

Read more at 28 Jupyter Notebook tips, tricks and shortcuts


In [ ]:
# Get help with a command by putting ? in front of it.
?print

In [ ]:
# Run file on your computer.
%run 00-hello-world.py

In [ ]:
%%time 
# How long does the code take to execute? Put %%time at the top to find out.
# Loop 10 million times.
for i in range(10000000):
    pass

Python as a calculator


In [ ]:
10 + 5

Variabes

Assign values to a variable. Variable names must start with a letter. No spaces allowed. Digits are OK.


In [ ]:
Name = "John Doe"              # String.
Age = 40                       # Integer.
Height = 180.3                 # Float.
Married = True                 # Boolean (True/False).
Children = ["Emma", "Thomas"]  # List.

In [ ]:
# Print the contents of variable.
Age

In [ ]:
# Print many at the same time.
print(Name)
print(Age)
print(Height)
print(Married)
print(Children)

Change variables


In [ ]:
# Change the value.
Age = Age + 10
print(Age)

In [ ]:
# We can't add numbers to strings. We will get a "TypeError".
Name + Age

In [ ]:
# We need to convert age to string.
mytext = Name + str(Age)
print(mytext)

Strings and string manipulation


In [ ]:
text = "The quick brown fox jumps over the lazy dog"

In [ ]:
# Get single characters from the text string.
print(text[0])  # Get the first character
print(text[4])  # Get the fifth character

In [ ]:
# Show the characters between 4th and 9th position (the word "quick").
print(text[4:9])

In [ ]:
# Replace "dog" with "journalist.
text.replace("dog", "journalist")

In [ ]:
# Make the text upper case, lower case, or title case.
print(text.upper())
print(text.lower())
print(text.title())

In [ ]:
# Get the length of the text string.
len(text)

In [ ]:
# Find where the position where "dog" starts.
print(text.find("dog"))

# If we search for something that is not in the text string, -1 will be returned.
print(text.find("candy"))

In [ ]:
# Lets combine many things!

# First, we save the text to a new variable so we can keep the old.
newtext = text

# Then, we do a lot of replacements.
newtext = newtext.replace("quick", "depressed")
newtext = newtext.replace("fox", "elephant")
newtext = newtext.replace("lazy", "even more depressed")
newtext = newtext.replace("dog", "journalist")

# After that, we title case it to make it look prettier.
newtext = newtext.title()

print(newtext)

If-statements

  • if, elif, and else
  • Don't forget to indent
  • Checks whether expression is True or False

Comparisons

age == 25     # Equal
age != 25     # Does not equal
age > 25      # Above 25
age < 25      # Below 25
age >= 25     # 25 or above
age <= 25     # 25 or below

Combine comparisons

  • or means that any conditional have to be True
  • and means that all conditional have to be True
age == 18 and height == 175 or name == "Jonas"

In [ ]:
# First, we assign a value to the variable "Name" and "Age".
Name = "John Doe"
Age = 40

# Check if age equals 40.
if Age == 40:
    print(Name + " is 40 years old.")
else:
    print(Name + " is not 40 years old.")

In [ ]:
# Lets change the age.
Age = 24

# Check many things at once: Is 40 years old? If not, is he above 40? If not,
# is he above 20 and below 40? If we can't find any match, run the code under "else".
if Age == 40:
    print(Name + " is 40 years old.")
elif Age > 40:
    print(Name + " is above 40 years old.")
elif Age > 20 and Age < 40:
    print(Name + " is above 20 and below 40.")
else:
    print(Name + " is 20 years or younger.")

For loops

  • range(to)
  • range(from, to, step)
  • can also use for with list

In [ ]:
# Loop 5 times.
for i in range(5):
    print(i)

In [ ]:
# Loop from 0 to 100, by ever 25.
for i in range(0, 100, 25):
    print(i)

In [ ]:
# We can use for loops on lists.
Children = ["Emma", "Thomas", "Nicole"]    # Make a list with 3 text strings.

for child in Children:
    print(child)

In [ ]:
# We can use for loops on numbers.
YearsOld = [14, 5, 4]    # Make a list with 3 numbers.

for age in YearsOld:
    print(age)

Functions

Group things together with functions.


In [ ]:
# A function that we name "calc" that multiples two numbers together. 
# It takes to variables as input (x and y).
# The function then returns the results of the multiplication.
def calc(x, y):
    return(x * y)

In [ ]:
# Now we just use the name of the function.
calc(10, 5)

Combine everything

Now it's time to combine everything we learned so far. By combining these techniques we can write quite complex programs.

Lets say we have a list of names. How many of the names start with the letter E?

This is how you do it in principle:

  1. You go through the list, name by name, with a for loop.
  2. For each name, you extract the first letter.
  3. If the first letter is an "E", you increase a counter with 1.

That's it!


In [ ]:
# Long list with names.
names = ["Adelia", "Agustin", "Ahmed", "Alethea", "Aline", "Alton", "Annett", "Arielle", "Billie", 
         "Blake", "Brianne", "Bronwyn", "Charlesetta", "Cleopatra", "Colene", "Corina", "Cruz", 
         "Curt", "Dawn", "Delisa", "Dolores", "Doloris", "Dominic", "Donetta", "Dusti", "Edna", 
         "Eliana", "Elna", "Emma", "Eugenio", "Francie", "Francisca", "Georgeanna", "Gerald", 
         "Gerry", "Gisele", "Hee", "Heidy", "Howard", "Iris", "Irving", "Izola", "Ja", "Jacinta", 
         "Jamey", "Jana", "Jeanie", "Jeffry", "Joeann", "Jonna", "Juliann", "Kacey", "Kandra", 
         "Karissa", "Kecia", "Kisha", "Leila", "Leslee", "Lisbeth", "Lizzette", "Lorie", "Luanna", 
         "Lynelle", "Lynna", "Lynnette", "Maire", "Maricela", "Mario", "Marsha", "Maxwell", 
         "Meggan", "Miquel", "Mireya", "Nakisha", "Natacha", "Nathanial", "Niesha", "Norberto", 
         "Norene", "Patrick", "Phoebe", "Phylicia", "Rashad", "Reatha", "Rebecka", "Renate", "Riley", 
         "Rochel", "Sadie", "Shawanna", "Sherri", "Sunshine", "Tamala", "Tish", "Vincent", "Yun"]

In [ ]:
# Create a variable that counts the number of names.
count = 0

for current_name in names:         # For loop that goes through each name in the list "names".
    if current_name[0] == "E":     # Is the first character the letter E?
        count = count + 1          # Add 1 to the variable "counter".

print("There are " + str(count) + " names that starts with the letter 'E'.")

In [ ]:
# Lets create a function so we can reuse the code.
# The function takes to inputs (names and letters),
# which is a list of names and the letter we want to look for.
def countnames(names, letter):
    count = 0                          # Create a variable that counts the number of names.
    for current_name in names:         # For loop that goes through each name in the list "names".
        if current_name[0] == letter:  # Is the first character the letter stored in the variable "letter"?
            count = count + 1          # Add 1 to the variable "counter".
    return(count)                      # At last, we return the counter.

# Call the functions with different letters (and save the results to variables).
e = countnames(names, "E")
f = countnames(names, "F")
p = countnames(names, "P")

# Print the results.
print("There are " + str(e) + " names that starts with the letter 'E'.")
print("There are " + str(f) + " names that starts with the letter 'F'.")
print("There are " + str(p) + " names that starts with the letter 'P'.")